package dp;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

/**
 * 1143. 最长公共子序列
 * 创建时间：2024/6/28 下午2:02
 */
public class 最长公共子序列_1143 {
    /**
     * DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j].
     *
     * DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise
     */
    public int longestCommonSubsequence(String text1, String text2) {
        int n1 = text1.length();
        int n2 = text2.length();
        int[][] dp = new int[n1 + 1][n2 + 1];
        for (int i = 1; i <= n1; i++) {
            char t1 = text1.charAt(i - 1);
            for (int j = 1; j <= n2; j++) {
                char t2 = text2.charAt(j - 1);
                if (t1 == t2) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
                }
            }
        }
        return dp[n1][n2];
    }

    public static void main(String[] args) {
        最长公共子序列_1143 a = new 最长公共子序列_1143();
        System.out.println(a.longestCommonSubsequence("abc", "def"));
    }

}
